#include "DDArr.h"
#include "Ddarr_r.h"
#include <string.h>
#include <stdlib.h>
#include <crtdbg.h>



static void *Ddarr_ctor(void *_pSelf, va_list *app){
	 DDARR * pSelf = base_ctor(Ddarr, _pSelf, app);
	pSelf->size = va_arg(* app,size_t);
	pSelf->height = va_arg(* app,size_t);
	pSelf->width = va_arg(* app,size_t);
	pSelf->data = (void *)malloc (sizeof(char)*pSelf->size * pSelf->height * pSelf->width);
	return pSelf;
	
}

static void* Ddarr_dtor (void* _self){
		DDARR *pSelf = _self;
		_CrtCheckMemory();
		free(pSelf->data);
		return pSelf;
}


static OBJECT_CLASS  ddarr_info;


const void * Ddarr = &ddarr_info;

void init_DdarrClass(void){

	inplace_new(
		&ddarr_info, 
		ObjectClass,   

		"Ddarr",       
		Object,          
		sizeof(DDARR), 

		ctor, Ddarr_ctor, 
		dtor, Ddarr_dtor, 
		0
	);
}

void *access(void *_pSelf,size_t x,size_t y){
	DDARR * pSelf = _pSelf;
	return (void *)(((char *)pSelf->data) + sizeof(char)*pSelf->size * (x + pSelf->width * y));
}

void copy_ddarr(DDARR *ar1, DDARR *ar2, size_t startx, size_t starty){
	if (ar1->size <= ar2->size){
		int i,j;
		void *now1;
		void *now2;
		for(i = 0 ; i < ar1->height ; i++ ){
			if (i == ar2->height){
				break;
			} else {
				for (j = 0 ; j < ar1->width ; j++){
					if (j + startx < ar2->width){
						now1 = access( ar1 , j , i );
						now2 = access( ar2 , j + startx , i + starty);
						memcpy(now2, now1, ar1->size);
					} else 
						break;
				}
			}
		}
	}
}


void reload_ddarr(void *_ar,size_t new_size , size_t new_height, size_t new_width){
	DDARR *ar = _ar;
	DDARR *new_arr = new(Ddarr, new_size, new_width, new_height);
	void* old_arr;
	_CrtCheckMemory();
	//copy_ddarr(ar,new_arr,0,0);
	_CrtCheckMemory();
	old_arr = ar->data;
	ar->data = new_arr->data;
	ar->height = new_arr->height;
	ar->size = new_arr->size;
	ar->width = new_arr->width;
	new_arr->data = old_arr;
	delete(new_arr);
}